import java.util.*;

public class Solution863 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }

        public TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
        }

        public TreeNode() {
        }
    }

    public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
        int[][] map=new int[600][600];
        dfs(root,map);
        List<Integer> ans=new ArrayList<>();
        int[] hash=new int[600];
        Queue<int[]> queue=new LinkedList<>();
        queue.offer(new int[]{target.val,0});
        hash[target.val]=1;
        while(!queue.isEmpty()){
            int[] t=queue.poll();
            if (t[1]==k){
                ans.add(t[0]);
            }else {
                for (int i = 0; i <= 500; i++) {
                    if (map[t[0]][i] == 1 && hash[i] == 0) {
                        hash[i] = 1;
                        queue.offer(new int[]{i,t[1]+1});
                    }
                }
            }
        }
        return ans;
    }
    void dfs(TreeNode node,int[][] map){
        if (node.left!=null){
            map[node.val][node.left.val]=1;
            map[node.left.val][node.val]=1;
            dfs(node.left,map);
        }
        if (node.right!=null){
            map[node.val][node.right.val]=1;
            map[node.right.val][node.val]=1;
            dfs(node.right,map);
        }
    }

    public static void main(String[] args) {
        TreeNode node5=new TreeNode(5,new TreeNode(6),new TreeNode(2,new TreeNode(7),new TreeNode(4)));
        TreeNode node3=new TreeNode(3,node5,new TreeNode(1,new TreeNode(0),new TreeNode(8)));
        System.out.println(new Solution863().distanceK(node3,node5,2));
    }
}
